import { _decorator, Component, input, Input, EventTouch, Vec2, Node, EventKeyboard, KeyCode, director, Label } from "cc";
import event from "../../utils/event";
import websocket from "../../utils/websocket";
const { ccclass, property } = _decorator;

export enum VisualAngle {
    "First" = 0.1,
    "Third" = 10,
}

@ccclass("Game/UI/Panel")
export class Panel extends Component {
    @property(Label)
    private btnSwitchVisualLabel: Label = null;

    private touchId: number = null;
    private startPos: Vec2 = null;
    private currentVisual = VisualAngle.Third;

    start() {
        input.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
        input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
        input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this);
        input.on(Input.EventType.TOUCH_CANCEL, this.onTouchEnd, this);

        input.on(Input.EventType.KEY_DOWN, this.handleKeyDown, this);
    }

    onTouchStart(e: EventTouch) {
        this.touchId = e.getID();
        this.startPos = e.getLocation();
        console.log("Panel onTouchStart", this.startPos);
    }

    onTouchMove(e: EventTouch) {
        if (this.touchId !== e.getID()) return;
        event.emit("panel.camera", { action: "move", delta: e.getDelta() });
    }

    onTouchEnd(e: EventTouch) {
        this.touchId = null;
        event.emit("panel.camera", { action: "reset", delta: e.getDelta() });
    }

    handleKeyDown(e: EventKeyboard) {
        if (e.keyCode === KeyCode.SPACE) {
            this.handleJump();
        }
    }

    handleJump() {
        event.emit("panel.jump");
        console.log("Panel handleJump");
    }

    handleBackToServerScene() {
        websocket.close();
        director.loadScene("server");
    }

    handleSwitchVisual() {
        if (this.currentVisual === VisualAngle.First) {
            this.currentVisual = VisualAngle.Third;
            this.btnSwitchVisualLabel.string = "第三人称";
        } else {
            this.currentVisual = VisualAngle.First;
            this.btnSwitchVisualLabel.string = "第一人称";
        }
        event.emit("panel.visual", this.currentVisual);
    }
}
